package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.wxpay.sdk.MyConfig;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lifeihu
 * @date 2021/11/28
 * @TIME:16:07
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);

        Map<String, String> map = orderService.submit(orders);
        return R.success(map);
    }
    @GetMapping("/page")
    public R findPage(Integer page, Integer pageSize, Long number, String beginTime, String endTime){
    Page<Orders> orders= orderService.findPage(page,pageSize,number,beginTime,endTime);
    return R.success(orders);
    }
    @GetMapping("/userPage")
    public R userPage(Integer page,Integer pageSize){
        Page<Orders> ordersPage=orderService.findUserPage(page,pageSize);
        return R.success(ordersPage);
    }
    /**
     * 输入流转换为xml字符串
     * @param
     * @return
     */
    @RequestMapping("/notifyAll")
    public void notifyOfWx(HttpServletRequest request, HttpServletResponse response){
        //触发描述
        System.out.println("支付成功回调。。。。");
        try {
            //输入流转换为xml字符串
            String xml = convertToString( request.getInputStream() );
            System.out.println(xml);
            //把xml 转换城一个Map集合
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            //获得是否成功的信息SUCCESS
            String result_code = map.get("result_code");
            if(!result_code.equals("SUCCESS")){
                throw new RuntimeException("支付失败，进行人工处理");
            }
            //返回值中有连个属性，最为重要
            //商家订单号。 根据订单号来修改数据库中订单的支付状态
            String out_trade_no = map.get("out_trade_no");

            //微信流水号 记录微信的支付凭证
            String transaction_id = map.get("transaction_id");

            //根据订单号，查询订单数据，
            Orders order = orderService.getById(out_trade_no);

            //修改支付状态为已支付
            order.setStatus(2);
            //更新数据库数据即可
            orderService.updateById(order);
            //需要更新微信调用的信息，来修改订单的状态为已支付
            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String convertToString(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inputStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        return result;
    }



    //查询订单的状态信息
    @GetMapping("/findStatusById")
    public R findStatusById(String orderId){

        //1.根据Id查询订单状态
        Orders order = orderService.getById(orderId);
        //2.判断状态是否为2
        if(order.getStatus() == 2){

            return R.success("支付成功");//code = 1
        }
        //3.如果状态为已支付。直接跳转 返回code 1
        return R.error("等待支付"); //code = 0

    }
}
